#include "convolutionfilter.h"

ConvolutionFilter::ConvolutionFilter()
{
    matrix = NULL;
    width = 0;
    height = 0;
}

ConvolutionFilter::ConvolutionFilter(int** matrix, int width, int height)
{
    this->matrix = matrix;
    this->width = width;
    this->height = height;
}

void ConvolutionFilter::filter(QImage* image)
{

    if(matrix == NULL)
        return;

    QImage orig = image->copy(0, 0, image->width(), image->height());

    int tx = (width - 1) / 2;
    int ty = (height - 1) / 2;

    int diviseur = 0;
    for(int i=0; i<width;i++){
        for(int j=0; j<height;j++){
            diviseur += matrix[i][j];
        }
    }
    if (diviseur == 0){
        diviseur = 1;
    }

    for(int y = 0; y < image->height(); y++) {
        for(int x = 0; x < image->width(); x++) {
            int r = 0;
            int g = 0;
            int b = 0;
            for(int l = 0; l < width; l++) {
                for(int c = 0; c < height; c++) {
                    int col = y + c - ty;
                    int lig = x + l - tx;
                    if(col < 0){
                        col = -col;
                    }
                    if(lig < 0){
                        lig = -lig;
                    }
                    if(col >= image->height()){
                        col = (image->height() * 2.0) - col - 1;
                    }

                    if(lig >= image->width()){
                        lig = (image->width() * 2.0) - lig - 1;
                    }
                    int tmpRgb = orig.pixel(lig, col);

                    r += ((qRed(tmpRgb))) * matrix[l][c];
                    g += ((qGreen(tmpRgb))) * matrix[l][c];
                    b += ((qBlue(tmpRgb))) * matrix[l][c];
                }
            }

            image->setPixel(x, y, qRgb((qMax(qMin(r/diviseur,255),0)), (qMax(qMin(g/diviseur,255),0)), (qMax(qMin(b/diviseur,255),0))));

        }
    }
}
